<!--
  文件名: Homepage.vue
  描述: 这是一个首页界面，是一个组件。参考界面为看雪论坛首页，知乎首页
  作者: 白紫铜
  创建日期: 2024-03-05
-->
<template>
  <div class="homepage">
      <el-container>
        <el-aside class="aside" width="150px"></el-aside>
        <el-container>
        <el-header class="header" >
          <el-row>
            <el-col :span="18" class="col_0">
              <el-carousel style="width: 95%">
                <el-carousel-item style="width: 100%;height: 100%">
                  <img alt="blockchain_technology_exploration" src="@/assets/blockchain0.jpg" style="width: 100%;height: 100%"/>
                </el-carousel-item>
                <el-carousel-item style="width: 100%;height: 100%">
                  <img alt="blockchain_technology_exploration" src="@/assets/区块链金融发展.png" style="width: 100%;height: 100%"/>
                </el-carousel-item>
                <el-carousel-item style="width: 100%;height: 100%">
                  <img alt="ad" src="@/assets/ad.png" style="width: 100%;height: 100%"/>
                </el-carousel-item>
              </el-carousel>
            </el-col>
            <el-col :span="6" class="col_1">
              <el-tooltip content="区块链重点项目走势表">
              <el-button class="button_top_right" @click="gotoFinancialProjects">
                <el-icon size="25px"><Histogram /></el-icon>
            </el-button>
              </el-tooltip>
              <el-tooltip content="区块链新闻速览">
                <el-button class="button_top_right">
                  <el-icon size="25px"><Notebook /></el-icon>
                </el-button>
              </el-tooltip>
              <div></div>
              <el-tooltip content="打赏站长">
              <el-button class="button_top_right" @click="rewardWebmaster">
                <el-icon size="25px" ><Coin /></el-icon>
              </el-button>
              </el-tooltip>
              <el-tooltip content="本站使用手册">
                <el-button class="button_top_right">
                  <el-icon size="25px"><Document /></el-icon>
                </el-button>
              </el-tooltip>
            </el-col>
          </el-row>
        </el-header>
        <el-main class="main">
          <el-row>
            <el-col :span="17" class="col_2">
          <el-tabs class="tabs_0" type="border-card">
            <el-tab-pane label="关注" class="tab_pane">
              <div v-if="focus_blogs.length === 0">
                <el-empty description="暂无关注的博客"></el-empty>
              </div>
              <el-row v-for="blog in focus_blogs" :key="blog.id">
                <div class="blog-info">
                  <img :src="blog.coverUrl" alt="博客封面" style="display: flex; height: 135px;width: 240px;align-items: center;text-align: center">
                  <div class="blog-info-details">
                    <el-link @click="gotoBlogDetails(blog)" class="blog-info-title">{{ blog.title }}</el-link>
                    <div class="blog-info-description">{{ blog.summary }}</div>
                    <el-link class="blog-info-author">作者：{{ blog.author.username }}</el-link>
                    <div class="blog-info-created-at">创建时间：{{ formatDate(blog.createdAt) }}</div>
                    <span class="blog-info-created-at">标签：{{ blog.tags }}</span>
                  </div>
                </div>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="推荐" class="tab_pane">

              <el-row v-for="blog in blogs" :key="blog.id">
                <div class="blog-info">
                  <img :src="blog.coverUrl" alt="博客封面" style="display: flex; height: 135px;width: 240px;align-items: center;text-align: center">
                  <div class="blog-info-details">
                    <el-link @click="gotoBlogDetails(blog)" class="blog-info-title">{{ blog.title }}</el-link>
                    <div class="blog-info-description">{{ blog.summary }}</div>
                    <el-link class="blog-info-author">作者：{{ blog.author.username }}</el-link>
                    <div class="blog-info-created-at">创建时间：{{ formatDate(blog.createdAt) }}</div>
                    <span class="blog-info-created-at">标签：{{ blog.tags }}</span>
                  </div>
                </div>
              </el-row>
            </el-tab-pane>
          </el-tabs>
            </el-col>
          </el-row>
          <div ref="loadMoreTrigger" style="height: 10px;"></div>
        </el-main>
        </el-container>
      </el-container>
  </div>
</template>

<script>
import {Coin, Document, Histogram, Notebook} from "@element-plus/icons-vue";
import axios from "axios";

export default {
  name: 'HomePage',
  components: {Notebook, Histogram, Document, Coin},
  props: {
    msg: String
  },
  data(){
    return{
      username:"",
      blogs:[],
      page:0,
      focus_page:0,
      pagesize:10,
      loading:false,
      observer: null,
      focus_blogs:[],
    }
  },
  computed:{
  },
  mounted() {
    const token=localStorage.getItem("token")
    axios.get('http://47.113.225.21:1145/api/get_followed_posts',{
      headers:{
        Authorization:`Bearer ${token}`
      },
      params:{
        user_id:localStorage.getItem("user_id"),
        page:this.focus_page,
        pageSize:this.pageSize
      }
    }).then(response=>{
      this.focus_blogs=this.focus_blogs.concat(response.data.content)
      this.focus_page++;
      this.loading=false
    }).catch(error => {
      console.error('获取博客数据失败', error);
      this.loading = false;
    });
    // 初始化 Intersection Observer
    this.observer = new IntersectionObserver(this.handleIntersection, {
      root: null,
      rootMargin: '0px',
      threshold: 0.1, // 当目标元素的10%进入视口时触发回调
    });

    // 监听加载更多数据的元素
    this.observer.observe(this.$refs.loadMoreTrigger);
  },
  beforeUnmount() {
    // 销毁 Intersection Observer
    if (this.observer) {
      this.observer.disconnect();
    }
  },
  methods:{
    rewardWebmaster(){
      const isAuthenticated=localStorage.getItem('token')
      if(!isAuthenticated){
        this.$message({
          type:"warning",
          message:"想要打赏站长请先登录"
        })
      }else {
        this.$confirm('确定要打赏站长吗','打赏站长',{
          confirmButtonText:"有的是钱",
          cancelButtonText:"才不给你呢",
          type:"info"
        }).then(()=>{
          this.$alert('<div class="images-container">\n' +
              '      <img src="/CNY.png" style="width: 100%;" alt="USDT">\n' +
              '      <img src="/USDT.jpg" style="width: 100%;" alt="CNY">\n' +
              '    </div>','V或U支付',{
            dangerouslyUseHTMLString:true,
            confirmButtonText:"OK"
          }).then(()=>{
            this.$message({
              type:"success",
              message:"谢谢您的支持！"
            })
          }).catch(()=>{
            this.$message({
              type:"info",
              message:"已取消打赏"
            })
          })
        }).catch(()=>{
          this.$message({
            type:"info",
            message:"已取消打赏"
          })
        })
      }
    },
    fetchBlogs(){
      const token=localStorage.getItem('token')
      const config={
        headers:{
          Authorization:`Bearer ${token}`
        },
        params:{
          page:this.page,
          pageSize:this.pagesize
        }
      }
      axios.get('http://47.113.225.21:1145/all_blogs',config)
          .then(response=>{
        this.blogs=this.blogs.concat(response.data.content)
        this.page++
        this.loading=false
      }).catch(error => {
        console.error('获取博客数据失败', error);
        this.loading = false;
      });
    },
    formatDate(dateTime) {
      const date = new Date(dateTime);
      // 获取日期的年、月和日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1，并且确保是两位数
      const day = String(date.getDate()).padStart(2, '0'); // 日，确保是两位数

      // 拼接成日期格式
      return `${year}-${month}-${day}`;
    },
    // Intersection Observer 回调函数
    handleIntersection(entries) {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          // 当加载更多数据的元素进入视口时，加载更多数据
          this.fetchBlogs();
        }
      });
    },
    gotoFinancialProjects(){
      this.$router.push({name:"FinancialProjects"})
    },
    gotoBlogDetails(blog){
      this.$router.push({
            name:"BlogDetails",
            params:{
              user_id:blog.author.user_id,
              post_id:blog.id,
              title:encodeURIComponent(blog.title) // 编码标题，以防止特殊字符对路由造成影响
            }
          }
      )
    },
  }
}
</script>
<style scoped>
:deep(.el-carousel__item:nth-child(2n)) {
  background-color: #99a9bf !important;
}

:deep(.el-carousel__item:nth-child(2n + 1)) {
  background-color: #d3dce6 !important;
}
.aside{
  width: 200px;
  height: 100%;
}
.header{
  margin-top: 25px;
  width: 1050px;
  height: 300px;
}
.main{
  width: 1050px;
}
.col_0{
  width: 100%;
  height: 100%;
}
.col_1{
  width: 300px;
  height: 300px;
  background-color: #F5F7FA;
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
  text-align: center;
}
.col_2{
  width: 100%;
  height: 100%;
  background-color: #F5F7FA;
  box-shadow: 0 8px 16px rgba(0,0,0,0.1);
}
.button_top_right{
  height: 50px;
  width: 50px;
  border-radius: 0;
  background-color: black;
  color: white;
  margin-top: 20px;
}
.button_top_right:hover{
  background-color: #606266;
  transition: 0.3s ease;
  color: #EBEDF0;
}
.button_top_right:focus{
  background-color: black;
  color: #ffffff;
}
.images-container{
  display: flex;
}
:deep(.el-tabs--border-card>.el-tabs__header .el-tabs__item.is-active){
  color: #606266 !important;
  font-weight: bold;
}
:deep(.el-tabs--border-card>.el-tabs__header .el-tabs__item:not(.is-disabled):hover){
  color: #606266 !important;
  background-color: #ffffff;
}

.blog-info {
  display: flex;
  border: 1px solid #ccc;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  width: 100%;
}

.blog-info img {
  width: 150px;
  height: auto;
  margin-right: 20px;
}

.blog-info-details {
  flex-grow: 1;
}

.blog-info-title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #000;
}
.blog-info-title:hover{
  border-bottom: none !important;
}

.blog-info-description {
  margin-bottom: 10px;
  white-space: nowrap; /* 不换行 */
  overflow: hidden; /* 超出部分隐藏 */
  text-overflow: ellipsis; /* 超出部分用省略号表示 */
  width: 50ch; /* 最多显示15个字符 */
}


.blog-info-meta {
  display: flex;
  justify-content: space-between;
}

.blog-info-author,
.blog-info-created-at{
  font-size: 14px;
  color: black;
}
.blog-info-description {
  margin-top: 10px;
}
.el-link{
  color: black;
  text-decoration: none !important;
}
.el-link:hover{
  color: #606266;
  border-bottom: none !important;
  text-decoration: none !important;
}
.el-link::after{
  color: #606266;
  border-bottom: none !important;
  text-decoration: none !important;
}
</style>
